<template>
  <div style="width: 100%;height: 100%;">
    <el-card style="height: 80px;">
      <div style="overflow: hidden;height: 100%;">
        <h3 style="float: left;">添加预告片</h3>
        <el-button type="primary"
                   style="width: 150px;height: 40px;
                   float: right;margin-top: 20px"
                   @click="add">添加
        </el-button>
      </div>
    </el-card>
    <el-card style="height:650px;">
      <el-empty v-if="tableData.length === 0"
                style="height: 650px;"
                description="没有数据"/>
      <el-table :data="tableData"
                v-if="tableData.length > 0"
                style="margin-top: 20px;width: 100%;height: 650px">
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column prop="title" label="预告片标题" align="center"/>
        <el-table-column label="预告片图片" align="center">
          <template #default="scope">
            <el-image :src="BASE_URL + scope.row.thumbnail"
                      :alt="thumbnail"
                      style="width:260px;height:auto;"/>
          </template>
        </el-table-column>
        <el-table-column label="预告片" align="center">
          <template #default="scope">
            <video :src="BASE_URL + scope.row.videoUrl"
                   controls style="width:260px;height:auto;"/>
          </template>
        </el-table-column>
        <el-table-column label="预告片时长" align="center">
          <template #default="scope">
            {{ scope.row.minute }} : {{ scope.row.second }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="editPreview(scope.row.id)">编辑</el-button>
            <el-button type="danger" @click="deletePreview(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="previewVisible"
               :title="previewTitle"
               style="width: 1000px;padding: 40px;height: 380px;"
               :before-close="handleClose">
      <el-form label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="预告片标题">
              <el-input v-model="savePreviewParam.title"
                        style="width: 90%;" placeholder="请输入预告片标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预告片时长">
              <el-input id="time" type="text"
                        style="width: 30%;"
                        v-model="savePreviewParam.minute"
                        placeholder="(分)"/>
              <span style="margin: 0 5px;font-size: 22px;font-weight: bold">:</span>
              <el-input id="time" type="text"
                        style="width: 30%;"
                        v-model="savePreviewParam.second"
                        placeholder="(秒)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="预告片缩略图">
              <el-upload
                  v-model:file-list="thumbnailFileList"
                  v-model:action="actionUrl"
                  name="file"
                  limit="1"
                  list-type="picture-card"
                  :on-preview="handleThumbnailCardPreview"
                  :on-remove="handleRemove">
                <el-icon>
                  <Picture/>
                </el-icon>
              </el-upload>
              <el-dialog v-model="thumbnailVisible">
                <img :src="thumbnail" style="width: 400px;" :alt="thumbnail"/>
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预告片视频">
              <el-upload
                  v-model:file-list="previewFileList"
                  v-model:action="previewUrl"
                  multiple
                  list-type="text"
                  :on-remove="removePreview"
                  :limit="1">
                <el-button style="width: 150px;" type="primary">上传视频</el-button>
                <template #tip>
                  <div class="el-upload__tip">上传视频文件，支持格式：mp4，文件大小不超过1GB</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button type="danger"
                 style="float: right;margin-right: 15px"
                 @click="handleClose">取消
      </el-button>
      <el-button type="primary"
                 style="float: right;margin-right: 15px"
                 @click="savePreview">保存
      </el-button>
    </el-dialog>
    <el-button type="primary"
               @click="next"
               style="position: absolute;
                   top: 90%;right: 85px;">
      下一步
    </el-button>
    <el-button
        style="position: absolute;top: 90%;right: 15px;"
        @click="cancel"
        type="danger">
      取消
    </el-button>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import router from "@/router";

let filmId = new URLSearchParams(window.location.search).get('id');
const savePreviewParam = ref({
  filmId: '',
  title: '',
  minute: '',
  second: '',
  thumbnail: '',
  videoUrl: ''
});

const tableData = ref([]);
const previewVisible = ref(false);
const previewTitle = ref('添加预告片');

const thumbnailFileList = ref([]);
const thumbnail = ref('');
const thumbnailVisible = ref(false);
const actionUrl = ref(BASE_URL + '/v1/thumbnail/upload');
const handleRemove = (uploadFile, uploadFiles) => {
  let thumbnailUrl = uploadFile.response?.data;
  if (thumbnailUrl) {
    axios.post(BASE_URL + '/v1/thumbnail/remove?thumbnailUrl=' + thumbnailUrl)
        .then(response => response.data.code === 2000 && ElMessage.success('删除成功!'));
  }
};

const handleThumbnailCardPreview = (uploadFile) => {
  thumbnail.value = uploadFile.url;
  thumbnailVisible.value = true;
};


const previewFileList = ref([]);
const previewUrl = ref(BASE_URL + '/v1/preview/upload');
const removePreview = (uploadFile, uploadFiles) => {
  let previewUrl = uploadFile.response?.data;
  if (previewUrl) {
    axios.post(BASE_URL + '/v1/preview/remove?previewUrl=' + previewUrl)
        .then(response => response.data.code === 2000 && ElMessage.success('删除成功!'));
  }
};

const add = () => {
  previewTitle.value = '添加预告片';
  previewVisible.value = true;
};

const savePreview = () => {
  if (savePreviewParam.value.title === null || savePreviewParam.value.title === '') {
    errorInfo('预告片标题不能为空');
    return;
  }
  if (savePreviewParam.value.minute === '' || savePreviewParam.value.minute === null) {
    errorInfo('预告片时长不能为空');
    return;
  }
  if (savePreviewParam.value.second === '' || savePreviewParam.value.second === null) {
    errorInfo('预告片时长不能为空');
    return;
  }
  if (savePreviewParam.value.minute < 0 || savePreviewParam.value.minute > 59) {
    errorInfo('预告片时长不合法');
    return;
  }
  if (thumbnailFileList.value.length === 0) {
    errorInfo('预告片缩略图不能为空');
    return;
  }
  if (previewFileList.value.length === 0) {
    errorInfo('预告片视频不能为空');
    return;
  }
  savePreviewParam.value.filmId = filmId;
  savePreviewParam.value.thumbnail = thumbnailFileList.value[0].response.data;
  savePreviewParam.value.videoUrl = previewFileList.value[0].response.data;
  let data = qs.stringify(savePreviewParam.value);
  console.log(data);
  axios.post(BASE_URL + '/v1/preview/save', data)
      .then(response => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          selectPreview()
          previewVisible.value = false;
          savePreviewParam.value = {};
          thumbnailFileList.value = [];
          previewFileList.value = [];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });

};

const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    previewVisible.value = false;
    savePreviewParam.value = {
      title: '',
      minute: '',
      second: '',
      thumbnail: '',
      videoUrl: ''
    };
    thumbnailFileList.value = [];
    previewFileList.value = [];
  }).catch(() => {
    //取消没有操作
  });
};


const selectPreview = () => {
  axios.get(BASE_URL + '/v1/preview/selectByFilmId/' + filmId)
      .then(response => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};
// 测试添加
onMounted(() => {
  selectPreview();
})

const editPreview = (id) => {
  previewVisible.value = true;
  previewTitle.value = '编辑信息';
  axios.get(BASE_URL + '/v1/preview/selectById/' + id)
      .then(response => {
        if (response.data.code === 2000) {
          savePreviewParam.value = response.data.data[0];
          previewFileList.value = [{
            url: BASE_URL + savePreviewParam.value.videoUrl,
            response: {data: savePreviewParam.value.videoUrl}
          }];
          thumbnailFileList.value = [{
            url: BASE_URL + savePreviewParam.value.thumbnail,
            response: {data: savePreviewParam.value.thumbnail}
          }];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};

const deletePreview = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/preview/delete/' + id)
        .then(response => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            selectPreview();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}

const next = () => {
  router.push('/insert/third?id='+ filmId)
};

const cancel = () => {
 ElMessageBox.confirm('确认取消吗？', '提示', {
   customClass: 'custom-message-box',
   confirmButtonText: '确定',
   cancelButtonText: '取消',
   type: 'warning',
   draggable: true,
 }).then(() => {
   axios.delete(BASE_URL + '/v1/preview/delete/film/' + filmId)
       .then(response => {
         if (response.data.code === 2000) {
           OKInfo('已取消保存!');
           selectPreview();
         } else {
           ElMessage({
             message: response.data.msg,
             type: 'error',
             showClose: true,
             center: true,
           });
         }
       })
   savePreviewParam.value = {};
   previewFileList.value = [];
   thumbnailFileList.value = [];
   router.push('/film')
 }).catch(() => {
 });
};
window.addEventListener('beforeunload', function (e) {
  var message = "您确定要离开此页面吗？未保存的数据可能会丢失。";
  e.returnValue = message;
  return message;
});
</script>

<style scoped>

</style>